package com;

import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wdl
 */
@WebServlet(name = "UserServlet")
public class UserServlet extends HttpServlet {
    private static final String CHECK_OPERATION="check";
    private static final String INSERT_OPERATION="insert";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //charset=utf-8使得可以显示中文
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        //从客户端获取数据
        String operation = request.getParameter("operation");
        String account = request.getParameter("account");
        //输出接收的信息
        System.out.println("操作：" + operation + "账号：" + account);
        //获得数据库操作对象
        CarDB cardb = new CarDB();
        //结果返回客户端
        JSONObject object = new JSONObject();
        //进行账号是否存在的检查
        if (operation.equals(CHECK_OPERATION)) {
            //查找账号是否存在，0存在，1不存在
            int result = cardb.checkAccountIfExist(account);
            object.put("result", result);
        } else if (operation.equals(INSERT_OPERATION)) {
            //账号的插入操作
            //从客户端获取数据
            String imageName = request.getParameter("image");
            String password = request.getParameter("password");
            String name = request.getParameter("name");
            int gender = Integer.parseInt(request.getParameter("gender"));
            String tel = request.getParameter("tel");
            int manager = 1;

            System.out.println(imageName + account + password + name + gender + tel);
            //创建实体类
            User user = new User(imageName, account, password, name, gender, tel, manager);
            //插入数据0代表失败，1代表成功
            int result = cardb.insertUser(user);
            object.put("result", result);
        }
        out.print(object);

        out.flush();
        out.close();
    }
}
